﻿using Common;
using IService;
using IService.SystemTableService;
using Microsoft.AspNetCore.Http;
using Model.Models;
using ModelDto;
using ModelDto.Request;
using ModelDto.Response;
using SqlserverManager;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.DirectoryServices.Protocols;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service.SystemTableService
{
    /// <summary>
    /// 在线聊天接口
    /// </summary>
    [Service]
    public class OnLineMsgService : IOnLineMsgService
    {
        private readonly IDbConnectionFactory _dbConnectionFactory;
        private readonly ISignalRSystemService _signalRSystemService;

        public OnLineMsgService(IDbConnectionFactory dbConnectionFactory, ISignalRSystemService signalRSystemService)
        {
            _dbConnectionFactory = dbConnectionFactory;
            _signalRSystemService = signalRSystemService;
        }
        /// <summary>
        /// 获取好友聊天最近一条消息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<GetUserMsgFirstListResonse>?> GetUserMsgFirstList(DeleteMoreRequest request, Account account)
        {
            if (request.IdArry == null || request.IdArry.Any() == false)
            {
                return null;
            }

            request.IdArry = request.IdArry.Where(a => !string.IsNullOrWhiteSpace(a)).Distinct().ToList();
            if (request.IdArry == null || request.IdArry.Any() == false)
            {
                return null;
            }
            var db = _dbConnectionFactory.CreateDbContext();

            var list = await db.Queryable<OnLineMsg>()
                .Where(a => (request.IdArry.Contains(a.User1) && a.User2 == account.Id) || (request.IdArry.Contains(a.User2) && a.User1 == account.Id))
                .ToListAsync();

            List<GetUserMsgFirstListResonse> resList = new List<GetUserMsgFirstListResonse>();
            if (list != null && list.Any())
            {
                foreach (var item in request.IdArry)
                {
                    GetUserMsgFirstListResonse temp = new GetUserMsgFirstListResonse();

                    var tempFirst = list.Where(a => a.User1 == item || a.User2 == item).OrderByDescending(a => a.CreateTime).FirstOrDefault();
                    temp.Msg = tempFirst?.Msg ?? "";
                    temp.Time = tempFirst?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "";
                    temp.UserId = item;

                    resList.Add(temp);
                }
            }

            return resList;
        }

        /// <summary>
        /// 获取好友聊天记录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<GetOnLineMsgListResonse>?> GetOnLineMsgList(DelRequest request, Account account)
        {
            if (string.IsNullOrWhiteSpace(request.Id))
            {
                return null;
            }
            var db = _dbConnectionFactory.CreateDbContext();
            var user2 = await db.Queryable<Account>().SingleAsync(a => a.Id == request.Id);
            if (user2 == null)
            {
                return null;
            }

            var list = await db.Queryable<OnLineMsg>()
                .Where(a => (a.User1 == request.Id && a.User2 == account.Id) || (request.Id == a.User2 && a.User1 == account.Id))
                .OrderBy(a => a.CreateTime)
                .ToListAsync();


            List<GetOnLineMsgListResonse> resList = new List<GetOnLineMsgListResonse>();
            if (list != null && list.Any())
            {
                foreach (var item in list)
                {
                    GetOnLineMsgListResonse temp = new GetOnLineMsgListResonse();

                    if (item.User1 == account.Id)
                    {
                        temp.State = 1;
                    }
                    else
                    {
                        temp.State = 2;
                    }
                    temp.Id = item.Id;
                    temp.Msg = item.Msg;
                    temp.HeadUrl = "";
                    temp.Time = item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    resList.Add(temp);
                }
            }

            return resList;
        }


        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<(bool, string)> SendMsg(SendMsgRequest request, Account account)
        {
            if (string.IsNullOrWhiteSpace(request.Id))
            {
                return new(false, "聊天对象找不到");
            }
            if (string.IsNullOrWhiteSpace(request.Msg))
            {
                return new(false, "发送消息不能为空");
            }
            var db = _dbConnectionFactory.CreateDbContext();
            var user2 = await db.Queryable<Account>().SingleAsync(a => a.Id == request.Id);
            if (user2 == null)
            {
                return new(false, "聊天对象异常");
            }

            OnLineMsg entity = new OnLineMsg();

            entity.Id = Guid.NewGuid().ToString("N");
            entity.User1 = account.Id;
            entity.User2 = request.Id;
            entity.Remark = "";
            entity.Msg = request.Msg;
            entity.State = 1;

            entity.DeleteUser = "";
            entity.UpdateUser = "";
            entity.IsDelete = false;
            entity.CreateTime = DateTime.Now;
            entity.CreateUser = account.Id;

            var res = await db.Insertable<OnLineMsg>(entity).ExecuteCommandAsync();
            if (res > 0)
            {
                await _signalRSystemService.ReceiveMsg(account.Id, request.Msg);
                return new(true, "发送成功");
            }
            return new(false, "发送失败");
        }
    }
}
